import { create } from 'zustand';

// 定义棋子常量
export const PIECES = {
  EMPTY: 0,
  PLAYER1: 1,
  PLAYER2: 2,
};

// 创建井字棋游戏状态存储
export const tcsStore = create((set) => ({
  // 初始状态
  piece: new Array(9).fill(PIECES.EMPTY),
  lines: [],

  // 放置棋子
  setPieceIndex: (index, user) =>
    set((state) => {
      // 检查游戏是否结束或位置已被占用
      if (state.piece[index] !== 0) {
        return state;
      }
      const oldlist = state.piece;
      // 更新棋盘
      const newPiece = state.piece.with(index, user);

      return {
        piece: newPiece,
        lines: [...state.lines, oldlist],
      };
    }),
  chPiece: () =>
    set((state) => {
      if (state.lines.length === 0) return state; // 如果 lines 为空，不做任何操作

      // 获取最后一步的棋盘状态
      const lastBoardState = state.lines[state.lines.length - 1];
      if (lastBoardState === undefined) return state;

      // 直接使用上一步的完整棋盘状态
      const newPiece = [...lastBoardState];

      // 创建新的历史记录数组，移除最后一步
      const newLines = state.lines.slice(0, -1);

      return {
        piece: newPiece,
        lines: newLines,
      };
    }),
  // 重置游戏
  resetGame: () =>
    set({
      piece: new Array(9).fill(PIECES.EMPTY),
      lines: [],
    }),
}));
